package com.huluobo.a2202mvvm_im_douyindemo.cart;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;
import com.huluobo.a2202mvvm_im_douyindemo.R;
import com.huluobo.a2202mvvm_im_douyindemo.adapter.CartAdapter;
import com.huluobo.a2202mvvm_im_douyindemo.bean.CartBeanResult;
import com.huluobo.a2202mvvm_im_douyindemo.databinding.ActivityCartBinding;
import com.huluobo.a2202mvvm_im_douyindemo.mvvmBase.BaseMVVMActivity;

import java.util.ArrayList;
import java.util.List;

public class CartActivity extends BaseMVVMActivity<ActivityCartBinding, CartViewModel> {

    private CartAdapter cartAdapter;

    private List<CartBeanResult.CartBean> cartBeanList = new ArrayList<>();

    @Override
    protected void initData() {
        viewModel.queryCartList();

        viewModel.getCartListSuccess.observe(this, cartBeanResult -> {
            if (cartBeanResult.getCode() == 200) {
                cartBeanList.clear();
                cartBeanList.addAll(cartBeanResult.getData());
                cartAdapter.notifyDataSetChanged();

                int totalPrice = 0;
                for (int i = 0; i < cartBeanList.size(); i++) {
                    totalPrice += cartBeanList.get(i).getCount() * cartBeanList.get(i).getGoods_default_price();
                }
                dataBinding.cartTotalPrice.setText("总价:" + totalPrice + "元");
            } else {
                ToastUtils.showLong(cartBeanResult.getMessage());
            }
        });

        viewModel.getCartListFailed.observe(this, s -> {
            Log.i("TagA", "获取购物车数据失败:" + s);
        });
    }

    @Override
    protected void intiView() {
        dataBinding.cartRv.setLayoutManager(new LinearLayoutManager(this));
        cartAdapter = new CartAdapter(cartBeanList);
        dataBinding.cartRv.setAdapter(cartAdapter);
    }

    @Override
    protected Class<CartViewModel> getViewModel() {
        return CartViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_cart;
    }
}